package fun.easycode.datastream;

import lombok.Getter;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;

/**
 * 流式查询结果处理器
 *  这种用于增量，全量使用生产者消费者模型实现
 * @author xuzhen97
 */
public class DataResultHandler<I> implements ResultHandler<I> {

    @Getter
    private final List<I> cache = new ArrayList<>();
    @Getter
    private final AtomicLong count = new AtomicLong(0);
    private static final int CACHE_SIZE = 1000;
    private final Consumer<List<I>> consumer;

    public DataResultHandler(Consumer<List<I>> consumer) {
        this.consumer = consumer;
    }

    @Override
    public void handleResult(ResultContext<? extends I> resultContext) {
        count.set(resultContext.getResultCount());
        if (cache.size() >= CACHE_SIZE) {
            consumer.accept(Collections.synchronizedList(new ArrayList<>(cache)));
            cache.clear();
        }
    }
}
